package com.hanxiaozhang.config;

import com.hanxiaozhang.constant.RabbitConstant;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * 〈一句话功能简述〉<br>
 * 〈Fanout交换机的Rabbit配置类〉
 *
 * @author hanxinghua
 * @create 2022/9/21
 * @since 1.0.0
 */
@Configuration
public class FanoutRabbitConfig implements BeanPostProcessor {
   
    @Resource
    private RabbitAdmin rabbitAdmin;

    /**
     * 队列A
     * @return
     */
    @Bean
    public Queue fanoutExchangeQueueA() {

        return new Queue(RabbitConstant.FANOUT_TOPIC_A, true, false, false);
    }

    /**
     * 队列B
     *
     * @return
     */
    @Bean
    public Queue fanoutExchangeQueueB() {

        return new Queue(RabbitConstant.FANOUT_TOPIC_B, true, false, false);
    }

    /**
     * 创建FanoutExchange类型交换机
     *
     * @return
     */
    @Bean
    public FanoutExchange rabbitFanoutExchange() {

        return new FanoutExchange(RabbitConstant.FANOUT_EXCHANGE, true, false);
    }

    /**
     * 队列A绑定到FanoutExchange交换机
     *
     * @return
     */
    @Bean
    public Binding bindFanoutA() {

        return BindingBuilder.bind(fanoutExchangeQueueA()).to(rabbitFanoutExchange());
    }

    /**
     * 队列B绑定到FanoutExchange交换机
     *
     * @return
     */
    @Bean
    public Binding bindFanoutB() {

        return BindingBuilder.bind(fanoutExchangeQueueB()).to(rabbitFanoutExchange());
    }

    /**
     * 启动项目即创建交换机和队列
     *
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        rabbitAdmin.declareExchange(rabbitFanoutExchange());
        rabbitAdmin.declareQueue(fanoutExchangeQueueB());
        rabbitAdmin.declareQueue(fanoutExchangeQueueA());
        return null;
    }
}
